package org.gitos.cloud.domain.tcp;

import java.io.Serializable;

/**
 * Created by shizhengchu on 16/1/13.
 */
public abstract class Field implements Serializable {

    //
    private byte[] value;

    // the length of value
    private int length = 0;


    protected void init(int len) {
        this.length = len;
        value = new byte[len];
        for (int i = 0; i < len; i++) {
            value[i] = 0x00;
        }
    }


    public byte[] getValue() {
        return value;
    }

    public void setValue(byte[] value) {
        if (value == null) {
            throw new RuntimeException("deviceId must not null");
        }
        if (value.length != this.length) {
            throw new RuntimeException("deviceId must " + length + " bytes");
        }
        this.value = value;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    @Override
    public int hashCode() {
        if (this.value == null) {
            return super.hashCode();
        }

        int x = 0;
        for (int i = 0; i < this.value.length; i++) {
            x += this.value[i] << i * 8;
        }

        x = ((x >> 16) ^ x) * 0x45d9f3b;
        x = ((x >> 16) ^ x) * 0x45d9f3b;
        x = ((x >> 16) ^ x);
        return x;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Field)) {
            return false;
        }
        Field field = (Field) obj;
        if (this.length != field.getLength()) {
            return false;
        }
        if (this.value == null && field.getValue() == null) {
            return true;
        }
        for (int i = 0; i < this.value.length; i++) {
            if (this.value[i] != field.getValue()[i]) {
                return false;
            }
        }
        return true;
    }
}
